<template>
  <div class="common_block_div">
    <div class="">
      <!-- 搜索筛选区域 -->
      <el-form :model="queryParams" class="margin_t10" ref="queryForm">
        <!-- 第一行：搜索条件 -->
        <el-row :gutter="20">
          <!-- 关键字 -->
          <el-col :span="6">
            <FormItem label="关键字" :span="24" type="input" :form="queryParams" @keyenter="handleQuery" prop="keywords" clearable placeholder="请输入关键字" />
          </el-col>

          <!-- 机构类型 -->
          <el-col :span="6">
            <FormItem label="机构类型" :span="24" type="select" :form="queryParams" prop="jg_category_id"
              :seleDatas="categoryOptions" seleKey="value" seleName="label" clearable
              placeholder="请选择机构类型" :loading="categoryLoading" />
          </el-col>

          <!-- 审核状态 -->
          <el-col :span="6">
            <FormItem label="审核状态" :span="24" type="select" :form="queryParams" prop="sq_status"
              :seleDatas="auditStatusOptions" seleKey="value" seleName="label" clearable
              placeholder="请选择审核状态" />
          </el-col>

          <!-- 省市区搜索 -->
          <el-col :span="6">
            <el-form-item label="所在地区">
              <el-cascader
                v-model="queryParams.location"
                :options="areaCascaderOptions"
                :props="cascaderProps"
                placeholder="请选择省/市/区"
                clearable
                style="width: 100%;"
                @change="handleSearchLocationChange"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：操作按钮 -->
        <el-row :gutter="20" style="margin-top: 10px;">
          <el-col :span="12">
            <div class="search_btns">
              <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
              <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </div>
          </el-col>
          <el-col :span="12" style="text-align: right;">
            <el-button type="primary" @click="handleAdd" v-if="have_auth('/institution/index/add')">新增</el-button>
          </el-col>
        </el-row>
      </el-form>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="list" style="width: 100%">
        <el-table-column label="集合编号" prop="id" width="120" />
        <el-table-column label="机构名称" prop="company_title" :show-overflow-tooltip="true" />
        <el-table-column label="机构类型" prop="jg_category_txt" width="150" />
        <el-table-column label="营业执照编号" prop="lic_no" width="200" />
        <el-table-column label="联系人" prop="username" width="140" />
        <el-table-column label="联系方式" prop="mobile" width="140" />

        <el-table-column label="省市区"  width="200px" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{scope.row.province_txt+scope.row.city_txt+scope.row.area_txt}}
          </template>
        </el-table-column>

        <el-table-column label="审核状态" prop="sq_status_txt" width="120" />
        <el-table-column label="操作" class-name="small-padding fixed-width" width="250px" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleView(scope.row)" v-if="have_auth('/institution/index/detail')">查看</el-button>
            <el-button size="mini" type="text" @click="handleEdit(scope.row)" v-if="have_auth('/institution/index/edit')">编辑</el-button>
            <el-button v-if="scope.row.sq_status === 0 && have_auth('/institution/index/shenhe')" size="mini" type="text"
              @click="handleAudit(scope.row)">审核</el-button>
            <el-button size="mini" type="text" style="color: #F56C6C;" @click="handleDelete(scope.row)" v-if="have_auth('/institution/index/del')">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.limit"
        @pagination="getList" />
    </div>

    <!-- 添加/编辑机构对话框 -->
    <el-dialog v-dialogDrag :close-on-click-modal="false" :title="dialogTitle" :visible.sync="dialogVisible"
      width="800px" append-to-body @closed="handleDialogClosed">
      <el-form ref="dialogForm" :model="form" :rules="rules" label-width="120px" label-position="left">
        <el-row>
          <!-- 机构名称 -->
          <el-col :span="24">
            <FormItem label="机构名称" :span="24" type="input" :form="form" prop="company_title" clearable
              placeholder="请输入机构名称" />
          </el-col>

          <!-- 机构类型 -->
          <el-col :span="24">
            <FormItem label="机构类型" :span="24" type="select" :form="form" prop="jg_category_id"
              :seleDatas="categoryOptions" seleKey="value" seleName="label" clearable
              placeholder="请选择机构类型" :loading="categoryLoading" />
          </el-col>

          <!-- 联系人 -->
          <el-col :span="24">
            <FormItem label="联系人" :span="24" type="input" :form="form" prop="username" clearable
              placeholder="请输入联系人姓名" />
          </el-col>

          <!-- 联系人手机 -->
          <el-col :span="24">
            <FormItem label="联系人手机" :span="24" type="input" :form="form" prop="mobile" clearable
              placeholder="请输入联系人手机号" />
          </el-col>

          <!-- 联系人邮箱 -->
          <el-col :span="24">
            <FormItem label="联系人邮箱" :span="24" type="input" :form="form" prop="email" clearable
              placeholder="请输入联系人邮箱" />
          </el-col>

          <!-- 登录密码 -->
          <el-col :span="24">
            <FormItem label="登录密码" :span="24" type="password" :form="form" prop="password" clearable
              placeholder="请输入登录密码" />
          </el-col>

          <!-- 省市区 -->
          <el-col :span="24">
            <el-form-item label="所在地区" prop="location">
              <el-cascader
                v-model="form.location"
                :options="areaCascaderOptions"
                :props="cascaderProps"
                placeholder="请选择省/市/区"
                clearable
                style="width: 100%;"
                @change="handleLocationChange"
              ></el-cascader>
            </el-form-item>
          </el-col>

          <!-- 详细地址 -->
          <el-col :span="24">
            <FormItem label="详细地址" :span="24" type="input" :form="form" prop="address" clearable
              placeholder="请输入详细地址" />
          </el-col>

          <!-- 上传营业执照 -->
          <el-col :span="24">
            <el-form-item label="上传营业执照" prop="lic_img">
              <SigleUpload :limit="1" :img="form.lic_img || ''" accept="image/*" class="black"
                type="picture-card" formkey="lic_img" form="form" @PicturePreview="PicturePreview"
                @handleUploadSuccess="handleUploadSuccess" @handleUploadRemove="handleUploadRemove" />
            </el-form-item>
          </el-col>

          <!-- 营业执照编号 -->
          <el-col :span="24">
            <FormItem label="营业执照编号" :span="24" type="input" :form="form" prop="lic_no" clearable
              placeholder="请输入营业执照编号" />
          </el-col>

          <!-- 机构描述 -->
          <el-col :span="24">
            <FormItem label="机构描述" :span="24" type="textarea" :form="form" prop="jg_desc" clearable
              placeholder="请输入机构描述" :rows="4" />
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('dialogForm')" :loading="is_ajax">
          {{ is_ajax ? '提交中...' : '确 定' }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 上传图片预览对话框 -->
    <el-dialog :close-on-click-modal="false" append-to-body @closed="uploadImageUrl = ''" width="600px"
      :visible.sync="uploadImgVisible">
      <img style="width: 100%;" :src="uploadImageUrl" alt="">
    </el-dialog>

    <!-- 查看机构详情对话框 -->
    <el-dialog v-dialogDrag :close-on-click-modal="false" title="查看机构详情" :visible.sync="viewDialogVisible" width="800px"
      append-to-body>
      <el-form :model="viewData" label-width="120px" label-position="left">
        <el-row>
          <!-- 机构名称 -->
          <el-col :span="24">
            <el-form-item label="机构名称">
              <span>{{ viewData.company_title || '-' }}</span>
            </el-form-item>
          </el-col>

          <!-- 机构类型 -->
          <el-col :span="24">
            <el-form-item label="机构类型">
              <span>{{ viewData.jg_category_txt || viewData.jg_category_id || '-' }}</span>
            </el-form-item>
          </el-col>

          <!-- 联系人 -->
          <el-col :span="24">
            <el-form-item label="联系人">
              <span>{{ viewData.username || '-' }}</span>
            </el-form-item>
          </el-col>

          <!-- 联系人手机 -->
          <el-col :span="24">
            <el-form-item label="联系人手机">
              <span>{{ viewData.mobile || '-' }}</span>
            </el-form-item>
          </el-col>

          <!-- 联系人邮箱 -->
          <el-col :span="24">
            <el-form-item label="联系人邮箱">
              <span>{{ viewData.email || '-' }}</span>
            </el-form-item>
          </el-col>

          <!-- 所在地区 -->
          <el-col :span="24">
            <el-form-item label="所在地区">
              <span>{{ getLocationText(viewData.province, viewData.city, viewData.area) || '-' }}</span>
            </el-form-item>
          </el-col>

          <!-- 详细地址 -->
          <el-col :span="24">
            <el-form-item label="详细地址">
              <span>{{ viewData.address || '-' }}</span>
            </el-form-item>
          </el-col>

          <!-- 营业执照图片 -->
          <el-col :span="24">
            <el-form-item label="营业执照">
              <div v-if="viewData.lic_img" style="margin-top: 10px;">
                <img :src="viewData.lic_img" alt="营业执照" style="max-width: 300px; max-height: 200px; cursor: pointer;"
                  @click="previewImage(viewData.lic_img)" />
              </div>
              <span v-else>-</span>
            </el-form-item>
          </el-col>

          <!-- 营业执照编号 -->
          <el-col :span="24">
            <el-form-item label="营业执照编号">
              <span>{{ viewData.lic_no || '-' }}</span>
            </el-form-item>
          </el-col>

          <!-- 机构描述 -->
          <el-col :span="24">
            <el-form-item label="机构描述">
              <span style="white-space: pre-wrap;">{{ viewData.jg_desc || '-' }}</span>
            </el-form-item>
          </el-col>

          <!-- 审核状态 -->
          <el-col :span="24">
            <el-form-item label="审核状态">
              <span>{{ viewData.sq_status_txt || '-' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog v-dialogDrag :close-on-click-modal="false" title="审核机构" :visible.sync="auditDialogVisible" width="500px"
      append-to-body @closed="handleAuditDialogClosed">
      <el-form ref="auditForm" :model="auditForm" :rules="auditRules" label-width="100px">
        <el-form-item v-if="showRejectReason" label="拒绝理由" prop="remark">
          <el-input v-model="auditForm.remark" type="textarea" :rows="4" placeholder="请输入拒绝理由" maxlength="200"
            show-word-limit />
        </el-form-item>
        <div v-else style="text-align: center; padding: 20px 0; color: #606266;">
          确定要通过该机构的审核吗？
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditDialogVisible = false">取 消</el-button>
        <el-button v-if="showRejectReason" type="danger" @click="handleAuditReject" :loading="auditLoading">
          {{ auditLoading ? '提交中...' : '确认拒绝' }}
        </el-button>
        <el-button v-else type="primary" @click="handleAuditApprove" :loading="auditLoading">
          {{ auditLoading ? '提交中...' : '同意' }}
        </el-button>
        <el-button v-if="!showRejectReason" type="danger" @click="showRejectReason = true" :disabled="auditLoading">
          拒绝
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入图片上传组件
import SigleUpload from "@/components/UploadImage/sigleUpload";
// 导入机构管理API
import organizationApi from "@/api/organization";
// 导入公共API
import publicApi from "@/api/public";

export default {
  name: 'needCache',
  components: {
    SigleUpload
  },
  data() {
    return {
      // 加载状态
      loading: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 查询参数
      queryParams: {
        page: 1,
        limit: 10,
        keywords: '',              // 关键字搜索
        jg_category_id: '',        // 机构类型
        sq_status: '',             // 审核状态
        location: [],              // 省市区级联选择器值 [provinceId, cityId?, areaId?]
        province: '',              // 省（搜索时使用）
        city: '',                  // 市（搜索时使用）
        area: ''                   // 区（搜索时使用）
      },
      // 账号类型映射
      accountTypeMap: {
        'enterprise': '企业',
        'association': '协会',
        'administrative': '行政机关',
        'foreign': '外资/合资企业'
      },
      // 对话框相关
      dialogVisible: false,
      dialogTitle: '新增机构',
      is_ajax: false,
      // 表单数据
      form: {
        id: '',
        company_title: '',           // 机构名称
        jg_category_id: '',          // 机构类型ID
        username: '',                // 联系人
        mobile: '',                  // 联系人手机
        email: '',                   // 联系人邮箱
        password: '',                // 登录密码
        location: [],                // 省市区级联选择器值 [provinceId, cityId, areaId]
        province: '',                // 省（提交时使用）
        city: '',                    // 市（提交时使用）
        area: '',                    // 区（提交时使用）
        address: '',                 // 详细地址
        lic_img: '',                 // 营业执照图片
        lic_no: '',                  // 营业执照编号
        jg_desc: ''                  // 机构描述
      },
      // 表单验证规则
      rules: {
        company_title: [
          { required: true, message: '机构名称不能为空', trigger: 'blur' }
        ],
        jg_category_id: [
          { required: true, message: '请选择机构类型', trigger: 'change' }
        ],
        username: [
          { required: true, message: '联系人不能为空', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '联系人手机不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '联系人邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        password: [
          {
            validator: (rule, value, callback) => {
              // 新增时密码必填，编辑时密码可选
              if (!this.form.id && !value) {
                callback(new Error('登录密码不能为空'));
              } else if (value && value.length < 6) {
                callback(new Error('密码长度不能少于6位'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        address: [
          { required: true, message: '详细地址不能为空', trigger: 'blur' }
        ],
        lic_no: [
          { required: true, message: '营业执照编号不能为空', trigger: 'blur' }
        ],
        jg_desc: [
          { required: true, message: '机构描述不能为空', trigger: 'blur' }
        ],
        lic_img: [
          { required: true, message: '营业执照不能为空', trigger: 'change' }
        ],
        location: [
          { required: true, message: '请选择所在地区', trigger: 'change' },
          { type: 'array', min: 3, message: '请完整选择省/市/区', trigger: 'change' }
        ]
      },
      // 机构类型选项
      categoryOptions: [],
      categoryLoading: false,
      // 审核状态选项
      auditStatusOptions: [],
      // 省市区级联选择器选项
      areaCascaderOptions: [],
      // 级联选择器配置
      cascaderProps: {
        value: 'id',
        label: 'title',
        children: '_child',
        expandTrigger: 'hover',
        checkStrictly: true,  // 允许选择任意级别的节点
        emitPath: true        // 返回路径数组，而不是只返回最后一级的值
      },
      // 上传图片相关
      uploadImageUrl: '',
      uploadImgVisible: false,
      // 查看对话框相关
      viewDialogVisible: false,
      viewData: {},
      // 审核对话框相关
      auditDialogVisible: false,
      auditLoading: false,
      showRejectReason: false,
      auditForm: {
        id: '',
        status: '',
        remark: ''
      },
      auditRules: {
        remark: [
          { required: true, message: '拒绝理由不能为空', trigger: 'blur' },
          { min: 2, max: 200, message: '拒绝理由长度在 2 到 200 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  activated() {
    this.getList();
    this.getCategories();
    this.getAuditStatus();
    this.getAreaCascaderData();
  },
  methods: {
    /** 查询列表数据 */
    getList() {
      const _this = this;
      this.loading = true;

      // 构建查询参数
      const params = {
        page: this.queryParams.page,
        limit: this.queryParams.limit
      };
      console.log(this.queryParams)
      // 添加搜索条件
      if (this.queryParams.keywords) {
        params.keywords = this.queryParams.keywords;
      }
      if (this.queryParams.jg_category_id) {
        params.jg_category_id = this.queryParams.jg_category_id;
      }
      if (this.queryParams.sq_status !== '') {
        params.sq_status = this.queryParams.sq_status;
      }
      // 添加省市区搜索条件（根据选择的节点传递相应参数）
      if (this.queryParams.province) {
        params.province = this.queryParams.province;
      }
      if (this.queryParams.city) {
        params.city = this.queryParams.city;
      }
      if (this.queryParams.area) {
        params.area = this.queryParams.area;
      }

      // 调用API获取机构列表
      organizationApi.list(params).then(function (res) {
        if (res && res.message) {
          _this.list = res.message.data || [];
          _this.total = res.message.total || 0;
        }
        _this.loading = false;
      }).catch(function (error) {
        console.error('获取机构列表失败:', error);
        _this.list = [];
        _this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        page: 1,
        limit: 10,
        keywords: '',
        jg_category_id: '',
        sq_status: '',
        location: [],
        province: '',
        city: '',
        area: ''
      };
      this.handleQuery();
    },

    /** 新建按钮操作 */
    handleAdd() {
      this.resetDialogForm();
      this.dialogTitle = '新增机构';
      this.dialogVisible = true;
    },

    /** 对话框关闭后的回调 */
    handleDialogClosed() {
      this.resetDialogForm();
    },

    /** 重置对话框表单 */
    resetDialogForm() {
      this.form = {
        id: '',
        company_title: '',
        jg_category_id: '',
        username: '',
        mobile: '',
        email: '',
        password: '',
        location: [],
        province: '',
        city: '',
        area: '',
        address: '',
        lic_img: '',
        lic_no: '',
        jg_desc: ''
      };
      if (this.$refs['dialogForm']) {
        this.$refs['dialogForm'].clearValidate();
      }
    },

    /** 提交表单 */
    submitForm(formName) {
      const _this = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.is_ajax = true;

          // 构建提交数据
          let submitData = {
            ...this.form
          };

          // 将级联选择器的 location 数组转换为 province/city/area
          if (this.form.location && Array.isArray(this.form.location) && this.form.location.length >= 3) {
            submitData.province = this.form.location[0];
            submitData.city = this.form.location[1];
            submitData.area = this.form.location[2];
          }
          // 删除 location 字段，不提交到后端
          delete submitData.location;

          // 编辑时，如果密码为空，则不提交密码字段
          if (this.form.id && !this.form.password) {
            delete submitData.password;
          }

          // 调用API创建或更新机构
          organizationApi.createOrUpdate(submitData).then(function (res) {
            if (res) {
              _this.tip_show('操作成功', 'success');
              _this.dialogVisible = false;
              _this.getList();
            }
            _this.is_ajax = false;
          }).catch(function (error) {
            console.error('操作失败:', error);
            _this.is_ajax = false;
            _this.tip_show('操作失败', 'error');
          });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },

    /** 上传图片预览 */
    PicturePreview(file) {
      this.uploadImageUrl = file.url;
      this.uploadImgVisible = true;
    },

    /** 上传成功回调 */
    handleUploadSuccess(res) {
      console.log(res);
      this[res.form][res.key] = res.url;
    },

    /** 删除上传的图片 */
    handleUploadRemove(res) {
      this[res.form][res.key] = '';
    },

    /** 查看按钮操作 */
    handleView(row) {
      // 填充查看数据
      this.viewData = {
        id: row.id || '',
        company_title: row.company_title || '',
        jg_category_id: String(row.jg_category_id) || '',
        jg_category_txt: row.jg_category_txt || '',
        username: row.username || '',
        mobile: row.mobile || '',
        email: row.email || '',
        province: row.province || '',
        city: row.city || '',
        area: row.area || '',
        address: row.address || '',
        lic_img: row.lic_img || '',
        lic_no: row.lic_no || '',
        jg_desc: row.jg_desc || '',
        sq_status_txt: row.sq_status_txt || ''
      };
      this.viewDialogVisible = true;
    },

    /** 审核按钮操作 */
    handleAudit(row) {
      this.auditForm = {
        id: row.id || '',
        status: '',
        remark: ''
      };
      this.showRejectReason = false;
      this.auditDialogVisible = true;
      // 清除表单验证
      this.$nextTick(() => {
        if (this.$refs.auditForm) {
          this.$refs.auditForm.clearValidate();
        }
      });
    },

    /** 同意审核 */
    handleAuditApprove() {
      const _this = this;
      this.auditLoading = true;
      organizationApi.audit({
        id: this.auditForm.id,
        status: 1,  // 1 表示同意
        remark: ''
      }).then((res) => {
        if (res) {
          _this.$message.success('审核通过');
          _this.auditDialogVisible = false;
          _this.getList();
        }
        _this.auditLoading = false;
      }).catch((error) => {
        console.error('审核失败:', error);
        _this.$message.error('审核失败');
        _this.auditLoading = false;
      });
    },

    /** 拒绝审核 */
    handleAuditReject() {
      const _this = this;
      this.$refs.auditForm.validate((valid) => {
        if (valid) {
          this.auditLoading = true;
          organizationApi.audit({
            id: this.auditForm.id,
            status: 2,  // 2 表示拒绝
            remark: this.auditForm.remark
          }).then((res) => {
            if (res) {
              _this.$message.success('审核已拒绝');
              _this.auditDialogVisible = false;
              _this.getList();
            }
            _this.auditLoading = false;
          }).catch((error) => {
            console.error('审核失败:', error);
            _this.$message.error('审核失败');
            _this.auditLoading = false;
          });
        } else {
          return false;
        }
      });
    },

    /** 审核对话框关闭后的回调 */
    handleAuditDialogClosed() {
      this.auditForm = {
        id: '',
        status: '',
        remark: ''
      };
      this.showRejectReason = false;
      if (this.$refs.auditForm) {
        this.$refs.auditForm.clearValidate();
      }
    },

    /** 编辑按钮操作 */
    handleEdit(row) {
      const _this = this;
      // 如果有ID，先获取详情数据
      if (row && row.id) {
        // 调用详情API获取完整数据（如果需要）
        // organizationApi.detail({ id: row.id }).then((res) => {
        //   if (res && res.message) {
        //     _this.form = {
        //       id: res.message.id || '',
        //       organization_name: res.message.organization_name || '',
        //       business_license_no: res.message.business_license_no || '',
        //       password: '', // 编辑时不显示密码
        //       business_license: res.message.business_license || '',
        //       introduction: res.message.introduction || ''
        //     };
        //   }
        //   _this.dialogTitle = '编辑机构';
        //   _this.dialogVisible = true;
        // }).catch((error) => {
        //   console.error('获取详情失败:', error);
        //   // 如果获取详情失败，使用列表数据
        //   _this.fillFormData(row);
        // });

        // 暂时直接使用列表数据填充表单
        _this.fillFormData(row);
      } else {
        // 新增模式
        _this.resetDialogForm();
        _this.dialogTitle = '新增机构';
        _this.dialogVisible = true;
      }
    },

    /** 填充表单数据 */
    fillFormData(row) {
      this.resetDialogForm();
      if (row) {
        // 将后端返回的 province/city/area 转换为级联选择器的 location 数组
        const location = [];
        if (row.province) location.push(row.province);
        if (row.city) location.push(row.city);
        if (row.area) location.push(row.area);

        this.form = {
          id: row.id || '',
          company_title: row.company_title || '',
          jg_category_id: String(row.jg_category_id) || '',
          username: row.username || '',
          mobile: row.mobile || '',
          email: row.email || '',
          password: '', // 编辑时不显示密码
          location: location, // 级联选择器值
          province: row.province || '', // 保留原值用于提交
          city: row.city || '',
          area: row.area || '',
          address: row.address || '',
          lic_img: row.lic_img || '',
          lic_no: row.lic_no || '',
          jg_desc: row.jg_desc || ''
        };
      }
      this.dialogTitle = row && row.id ? '编辑机构' : '新增机构';
      this.dialogVisible = true;
    },

    /** 获取机构类型列表 */
    getCategories() {
      const _this = this;
      this.categoryLoading = true;
      organizationApi.getCategories({}).then(function (res) {
        if (res && res.message) {
          _this.categoryOptions = res.message || [];
        }
        _this.categoryLoading = false;
      }).catch(function (error) {
        console.error('获取机构类型失败:', error);
        _this.categoryLoading = false;
      });
    },

    /** 获取审核状态列表 */
    getAuditStatus() {
      const _this = this;
      organizationApi.getAuditStatus({}).then(function (res) {
        if (res && res.message) {
          // 将接口返回的数据转换为下拉选项格式，兼容多种数据格式
          _this.auditStatusOptions = res.message
        }
      }).catch(function (error) {
        console.error('获取审核状态失败:', error);
        _this.auditStatusOptions = [];
      });
    },

    /** 获取省市区级联数据 */
    getAreaCascaderData() {
      const _this = this;
      // 调用API获取省市区数据
      publicApi.getArea().then(function (res) {
        if (res && res.message) {
          // 接口返回的数据已经是级联格式，直接使用
          // 返回值中 message 是数组，每个元素包含 id、title 和 _child 字段
          const data = Array.isArray(res.message) ? res.message : (res.message.data || res.message.list || []);
          _this.areaCascaderOptions = data;
        }
      }).catch(function (error) {
        console.error('获取省市区数据失败:', error);
        _this.areaCascaderOptions = [];
      });
    },

    /** 级联选择器变化回调 */
    handleLocationChange(value) {
      // value 是数组格式 [provinceId, cityId, areaId]
      // 这里可以做一些额外的处理，比如更新 form 中的 province/city/area
      if (value && Array.isArray(value) && value.length >= 3) {
        this.form.province = value[0];
        this.form.city = value[1];
        this.form.area = value[2];
      } else {
        this.form.province = '';
        this.form.city = '';
        this.form.area = '';
      }
    },

    /** 搜索表单级联选择器变化回调 */
    handleSearchLocationChange(value) {
      // value 是数组格式，可以是 [provinceId], [provinceId, cityId], 或 [provinceId, cityId, areaId]
      // 根据选择的节点数量设置相应的搜索参数
      if (value && Array.isArray(value) && value.length > 0) {
        // 重置所有省市区字段
        this.queryParams.province = '';
        this.queryParams.city = '';
        this.queryParams.area = '';

        // 根据选择的节点设置相应字段
        if (value.length >= 1) {
          this.queryParams.province = value[0];
        }
        if (value.length >= 2) {
          this.queryParams.city = value[1];
        }
        if (value.length >= 3) {
          this.queryParams.area = value[2];
        }
      } else {
        // 清空时重置所有字段
        this.queryParams.province = '';
        this.queryParams.city = '';
        this.queryParams.area = '';
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const _this = this;
      this.$confirm('是否确认删除该条数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        // 调用删除API
        organizationApi.delete({ id: row.id }).then((res) => {
          if (res) {
            _this.getList();
            _this.$message.success('删除成功');
          }
        }).catch((err) => {
          console.error('删除失败:', err);
          _this.$message.error('删除失败');
        });
      }).catch(() => {
        // 用户取消删除
      });
    },

    /** 获取账号类型标签 */
    getAccountTypeLabel(type) {
      return this.accountTypeMap[type] || type || '未知';
    },

    /** 根据省市区ID获取文本 */
    getLocationText(provinceId, cityId, areaId) {
      if (!provinceId && !cityId && !areaId) {
        return '';
      }

      let provinceText = '';
      let cityText = '';
      let areaText = '';

      // 从级联数据中查找省市区文本
      if (this.areaCascaderOptions && this.areaCascaderOptions.length > 0) {
        // 查找省份
        if (provinceId) {
          const province = this.areaCascaderOptions.find(item => item.id == provinceId);
          if (province) {
            provinceText = province.title || '';

            // 查找城市
            if (cityId && province._child && province._child.length > 0) {
              const city = province._child.find(item => item.id == cityId);
              if (city) {
                cityText = city.title || '';

                // 查找区县
                if (areaId && city._child && city._child.length > 0) {
                  const area = city._child.find(item => item.id == areaId);
                  if (area) {
                    areaText = area.title || '';
                  }
                }
              }
            }
          }
        }
      }

      // 拼接省市区文本
      const locationParts = [];
      if (provinceText) locationParts.push(provinceText);
      if (cityText) locationParts.push(cityText);
      if (areaText) locationParts.push(areaText);

      return locationParts.length > 0 ? locationParts.join(' / ') : '';
    },

    /** 预览图片 */
    previewImage(imageUrl) {
      if (imageUrl) {
        this.uploadImageUrl = imageUrl;
        this.uploadImgVisible = true;
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
